package org.chen.payment.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.chen.payment.dto.PaymentCallbackRequest;
import org.chen.payment.entity.PaymentCallbackLog;
import org.chen.payment.mapper.PaymentCallbackLogMapper;
import org.chen.payment.util.SignUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.internet.MimeMessage;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class PaymentCallbackService {
    
    private final PaymentCallbackLogMapper callbackLogMapper;
    private final JavaMailSender mailSender;

    @Value("${payment.merchant.key}")
    private String merchantKey; // 商户密钥，从配置文件读取

    @Value("${spring.mail.username}")
    private String mailFrom; // 发件人邮箱

    @Value("${payment.admin.email:1905333495@qq.com}")
    private String adminEmail; // 管理员邮箱
    
    /**
     * 处理支付回调
     * @param request 回调请求
     * @return 处理结果
     */
    @Transactional(rollbackFor = Exception.class)
    public String handlePaymentCallback(PaymentCallbackRequest request) {
        log.info("收到支付回调: {}", request);
        
        try {
            // 1. 验证签名
            boolean signValid = verifySign(request);
            log.info("签名验证结果: {}", signValid ? "通过" : "失败");
            
            // 2. 记录回调日志到数据库
            PaymentCallbackLog logEntity = new PaymentCallbackLog();
            BeanUtils.copyProperties(request, logEntity);
            logEntity.setSignValid(signValid);
            logEntity.setCreateTime(LocalDateTime.now());
            logEntity.setUpdateTime(LocalDateTime.now());
            
            callbackLogMapper.insert(logEntity);
            
            // 3. 验证签名失败的处理
            if (!signValid) {
                log.error("签名验证失败，订单号: {}", request.getOutTradeNo());
                return "fail"; // 签名验证失败返回FAIL
            }
            
            // 4. 验证支付状态
            if (!"TRADE_SUCCESS".equals(request.getTradeStatus())) {
                log.warn("支付状态不是成功状态: {}", request.getTradeStatus());
                return "success"; // 即使不是成功状态也返回success表示接收到了
            }
            
            // 5. 通知
            processPaymentSuccess(request);
            
            log.info("支付回调处理成功，订单号: {}", request.getOutTradeNo());
            return "success";
            
        } catch (Exception e) {
            log.error("处理支付回调异常: ", e);
            throw new RuntimeException("处理支付回调失败", e);
        }
    }
    
    /**
     * 验证签名
     * @param request 回调请求
     * @return 是否验证通过
     */
    private boolean verifySign(PaymentCallbackRequest request) {
        Map<String, Object> params = new HashMap<>();
        params.put("pid", request.getPid());
        params.put("trade_no", request.getTradeNo());
        params.put("out_trade_no", request.getOutTradeNo());
        params.put("type", request.getType());
        params.put("name", request.getName());
        params.put("money", request.getMoney());
        params.put("trade_status", request.getTradeStatus());

        return SignUtil.verifyMD5Sign(params, request.getSign(), merchantKey);
    }
    
    /**
     * 处理支付成功的业务逻辑
     * @param request 回调请求
     */
    private void processPaymentSuccess(PaymentCallbackRequest request) {
        log.info("处理支付成功业务逻辑，订单号: {}", request.getOutTradeNo());

        try {
            // 发送邮件通知管理员
            sendPaymentNotificationEmail(request);
            log.info("支付成功邮件通知已发送，订单号: {}", request.getOutTradeNo());
        } catch (Exception e) {
            log.error("发送支付通知邮件失败，订单号: {}, 错误: {}", request.getOutTradeNo(), e.getMessage(), e);
            // 注意：邮件发送失败不影响支付回调的成功响应
        }
    }

    /**
     * 发送支付成功通知邮件
     * @param request 支付回调请求
     */
    private void sendPaymentNotificationEmail(PaymentCallbackRequest request) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            // 设置发件人昵称和邮箱
            helper.setFrom(mailFrom, "智灵API");
            helper.setTo(adminEmail);
            helper.setSubject("💰 支付成功通知 - 订单号：" + request.getOutTradeNo());

            // 生成HTML邮件内容
            String htmlContent = generatePaymentEmailHtml(request);
            helper.setText(htmlContent, true);

            mailSender.send(message);

        } catch (Exception e) {
            log.error("发送邮件失败: ", e);
            throw new RuntimeException("邮件发送失败", e);
        }
    }

    /**
     * 生成支付通知邮件的HTML内容
     * @param request 支付回调请求
     * @return HTML邮件内容
     */
    private String generatePaymentEmailHtml(PaymentCallbackRequest request) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        return """
            <!DOCTYPE html>
            <html lang="zh-CN">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>支付成功通知</title>
                <style>
                    body {
                        font-family: 'Helvetica Neue', Arial, sans-serif;
                        line-height: 1.6;
                        margin: 0;
                        padding: 0;
                        background-color: #f4f4f4;
                    }
                    .container {
                        max-width: 600px;
                        margin: 20px auto;
                        background-color: #ffffff;
                        border-radius: 8px;
                        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                        overflow: hidden;
                    }
                    .header {
                        background: linear-gradient(135deg, #667eea 0%%, #764ba2 100%%);
                        color: white;
                        text-align: center;
                        padding: 30px 20px;
                    }
                    .header h1 {
                        margin: 0;
                        font-size: 28px;
                        font-weight: 300;
                    }
                    .header .icon {
                        font-size: 48px;
                        margin-bottom: 10px;
                    }
                    .content {
                        padding: 30px;
                    }
                    .success-message {
                        background-color: #d4edda;
                        border: 1px solid #c3e6cb;
                        border-radius: 6px;
                        color: #155724;
                        padding: 15px;
                        margin-bottom: 25px;
                        font-weight: 500;
                        text-align: center;
                    }
                    .info-table {
                        width: 100%%;
                        border-collapse: collapse;
                        margin: 20px 0;
                        background-color: #fff;
                    }
                    .info-table th {
                        background-color: #f8f9fa;
                        color: #495057;
                        font-weight: 600;
                        padding: 12px 15px;
                        text-align: left;
                        border-bottom: 2px solid #dee2e6;
                        width: 30%%;
                    }
                    .info-table td {
                        padding: 12px 15px;
                        border-bottom: 1px solid #dee2e6;
                        color: #212529;
                    }
                    .amount {
                        color: #28a745;
                        font-weight: bold;
                        font-size: 18px;
                    }
                    .status {
                        display: inline-block;
                        padding: 4px 12px;
                        background-color: #28a745;
                        color: white;
                        border-radius: 20px;
                        font-size: 12px;
                        font-weight: 500;
                    }
                    .footer {
                        background-color: #f8f9fa;
                        padding: 20px;
                        text-align: center;
                        color: #6c757d;
                        font-size: 14px;
                        border-top: 1px solid #dee2e6;
                    }
                    .footer .brand {
                        color: #667eea;
                        font-weight: 600;
                        text-decoration: none;
                    }
                    .time-info {
                        background-color: #e7f3ff;
                        border-left: 4px solid #007bff;
                        padding: 10px 15px;
                        margin: 15px 0;
                        font-size: 14px;
                        color: #004085;
                    }
                </style>
            </head>
            <body>
                <div class="container">
                    <div class="header">
                        <div class="icon">💰</div>
                        <h1>支付成功通知</h1>
                    </div>

                    <div class="content">
                        <div class="success-message">
                            ✅ 收到一笔新的支付成功通知！
                        </div>

                        <table class="info-table">
                            <tr>
                                <th>商户订单号</th>
                                <td><strong>%s</strong></td>
                            </tr>
                            <tr>
                                <th>易支付订单号</th>
                                <td>%s</td>
                            </tr>
                            <tr>
                                <th>商户ID</th>
                                <td>%d</td>
                            </tr>
                            <tr>
                                <th>商品名称</th>
                                <td>%s</td>
                            </tr>
                            <tr>
                                <th>支付金额</th>
                                <td class="amount">¥ %s</td>
                            </tr>
                            <tr>
                                <th>支付方式</th>
                                <td>%s</td>
                            </tr>
                            <tr>
                                <th>支付状态</th>
                                <td><span class="status">%s</span></td>
                            </tr>
                            <tr>
                                <th>业务参数</th>
                                <td>%s</td>
                            </tr>
                        </table>

                        <div class="time-info">
                            <strong>📅 通知时间：</strong> %s
                        </div>
                    </div>

                    <div class="footer">
                        <p>此邮件由 <a href="#" class="brand">智灵API</a> 系统自动发送</p>
                        <p>如有疑问，请及时检查系统日志或联系技术支持</p>
                    </div>
                </div>
            </body>
            </html>
            """.formatted(
                request.getOutTradeNo(),
                request.getTradeNo(),
                request.getPid(),
                request.getName(),
                request.getMoney(),
                getPaymentTypeDisplay(request.getType()),
                request.getTradeStatus(),
                request.getParam() != null ? request.getParam() : "无",
                now.format(formatter)
        );
    }

    /**
     * 获取支付方式的显示名称
     * @param type 支付方式代码
     * @return 显示名称
     */
    private String getPaymentTypeDisplay(String type) {
        return switch (type.toLowerCase()) {
            case "alipay" -> "支付宝";
            case "wxpay" -> "微信支付";
            default -> type;
        };
    }
}